package models

import (
	"crypto/rand"
	"fmt"
	"log"

	"gitee.com/anxu/golang-web/src/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Db *gorm.DB

func init() {
	dsn := config.Config.Get("db.dsn", "").(string)
	if dsn == "" {
		panic("Invalid config: db dsn")
	}
	Db = getDb(dsn)
	migrate(Db)
}

func migrate(db *gorm.DB) {
	db.AutoMigrate(&Post{}, &User{}, &Thread{})
}

func getDb(dns string) *gorm.DB {
	Db, err := gorm.Open(mysql.Open(dns), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}
	return Db
}

func createUUID() (uuid string) {
	u := new([16]byte)
	_, err := rand.Read(u[:])
	if err != nil {
		log.Fatalln("Cannot generate UUID", err)
	}

	// 0x40 is reserved variant from RFC 4122
	u[8] = (u[8] | 0x40) & 0x7F
	// Set the four most significant bits (bits 12 through 15) of the
	// time_hi_and_version field to the 4-bit version number.
	u[6] = (u[6] & 0xF) | (0x4 << 4)
	uuid = fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
	return
}
